<template>
  <el-dialog :title="title" v-if="dialogVisible" :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
    <div style="width: 98%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="90px" class="demo-ruleForm">
        <el-form-item label="关联方式" prop="relationType">
          <el-select v-model="ruleForm.relationType" placeholder="请选择关联方式" :disabled="isSelect">
            <el-option label="直接关联" value="1"></el-option>
            <el-option label="关联表关联" value="2"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="ruleForm.relationType == 1">
          <el-form-item label="模型连接">
            <template slot-scope="{ row }">
              <div ref="container"
                style="position: relative; width: 100%; height: 60vh; border: 1px solid black; overflow: auto"></div>
            </template>
          </el-form-item>
          <span style="display: flex; flex-direction: row; justify-content: flex-end">
            <el-form-item>
              <el-button @click="
                listoff()
              dialogVisible = false
              off()
              relationArr = []
                ">取 消</el-button>
              <el-button type="primary" @click.sync="overFun()">确 定</el-button>
            </el-form-item>
          </span>
        </template>

        <template v-if="ruleForm.relationType == 2">
          <el-row>
            <el-col :span="24">
              <el-form-item label="关联表" prop="dataType">
                <el-select v-model="ruleForm.relationTableid" filterable placeholder="请选择关联方式">
                  <el-option v-for="v in glaiboa" :key="v.id" :label="v.tableName" @change="optiongsClick(v.id)"
                    :value="v.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="isOpbool">
              <el-form-item label="模型连接">
                <template slot-scope="{ row }">
                  <div ref="associationTableContainer"
                    style="position: relative; width: 100%; height: 60vh; border: 1px solid black; overflow: auto">
                  </div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="生效时间">

                <template slot-scope="{ row }">
                  <el-date-picker v-model="timeArr" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期"> </el-date-picker>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
          <span style="display: flex; flex-direction: row; justify-content: flex-end">
            <el-form-item>
              <el-button @click="
                listoff()
              dialogVisible = false
              off()
              threerelationArr = []
                ">取 消</el-button>
              <el-button type="primary" @click.sync="gloverFun()">确 定</el-button>
            </el-form-item>
          </span>
        </template>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import G6 from '@antv/g6'
import { deletecaveasmodelid, associationTableDetail } from '@/api/masterdata/masterdataDirectory.js'
import { queryAssociationTable, fieldRelation } from '@/api/metadata/label/metadataLabel.js'
import { ifElse } from 'ramda'

export default {
  props: {
    isView: {
      type: Boolean,
    }
  },
  computed: {
    uniquestItem() {
      const unique = {}
      this.setArr.forEach(item => { unique[item.edgeId] = item })
      return Object.values(unique);
    },
    conArr() {
      console.log('执行了没有');
      const unique = {}
      this.concantArr.forEach(item => { unique[item.edgeId] = item })
      return Object.values(unique);
    }
  },
  data() {
    return {
      isFirst: true,
      title: '',
      index: '',
      type: '',
      isSelect: false,
      listtable: [],
      relationArr: [],
      arr: [],
      form: {
        primaryFieldid: '',
        primaryFieldname: '',
        relationFieldid: '',
        relationFieldname: '',
        secondaryFieldid: '',
        secondaryFieldname: '',
      },
      dialogVisible: false,
      timeArr: [], //时间
      glaiboa: [],
      isOpbool: false,

      relationTable: {
        relationType: '1', //1、直接关联；2、关联表关联
        name: undefined, //关系名称
        primaryTableid: undefined, //主表id
        primaryTablename: undefined, //主表名称
        primaryFieldid: undefined, //主表字段id
        primaryFieldname: undefined, //主表字段名称
        secondaryTableid: undefined, //次表id
        secondaryTablename: undefined, //次表名称
        secondaryFieldid: undefined, //次表字段id
        secondaryFieldname: undefined, //次表字段名称
        primarySecondaryConnectedrelationName: undefined, //主表和次表字段关联关系名称
        relationTableid: '', //关联表id
        relationTablename: undefined, //关联表名称
        relationFieldid: undefined, //关联表字段id
        relationFieldname: undefined, //关联表字段名称
        // uniqueCode: undefined, //primary_fieldid和primary_fieldid排序后的64位uuid的hashcode
        relationPrimaryFieldid: undefined, //关联表与主表的连接字段id
        relationSecondaryFieldid: undefined, //关联表与次表的连接字段id
        relationPrimaryFieldname: undefined, //关联表与主表的连接字段名称
        relationSecondaryFieldname: undefined, //关联表与次表的连接字段名称
        starttime: undefined, //生效时间
        endtime: undefined, //失效时间
        modelId: undefined, //元模型id
        // description: undefined, //描述
        relationPrimaryConnectedrelationName: undefined, //关联表和主表字段关联关系名称

        relationSecondaryConnectedrelationName: undefined, //关联表和次表字段关联关系名称,
        lxtype: '',
        lxtype1: '',
        lxtype2: '',
        lxtype3: '',
      },
      ruleForm: {
        relationType: '1', //1、直接关联；2、关联表关联
        name: undefined, //关系名称
        primaryTableid: undefined, //主表id
        primaryTablename: undefined, //主表名称
        primaryFieldid: undefined, //主表字段id
        primaryFieldname: undefined, //主表字段名称
        secondaryTableid: undefined, //次表id
        secondaryTablename: undefined, //次表名称
        secondaryFieldid: undefined, //次表字段id
        secondaryFieldname: undefined, //次表字段名称
        primarySecondaryConnectedrelationName: undefined, //主表和次表字段关联关系名称
        relationTableid: '', //关联表id
        relationTablename: undefined, //关联表名称
        relationFieldid: undefined, //关联表字段id
        relationFieldname: undefined, //关联表字段名称
        // uniqueCode: undefined, //primary_fieldid和primary_fieldid排序后的64位uuid的hashcode
        relationPrimaryFieldid: undefined, //关联表与主表的连接字段id
        relationSecondaryFieldid: undefined, //关联表与次表的连接字段id
        relationPrimaryFieldname: undefined, //关联表与主表的连接字段名称
        relationSecondaryFieldname: undefined, //关联表与次表的连接字段名称
        starttime: undefined, //生效时间
        endtime: undefined, //失效时间
        modelId: undefined, //元模型id
        // description: undefined, //描述
        relationPrimaryConnectedrelationName: undefined, //关联表和主表字段关联关系名称
        relationSecondaryConnectedrelationName: undefined, //关联表和次表字段关联关系名称,
        lxtype: '',
        lxtype1: '',
        lxtype2: '',
        lxtype3: '',
      },
      threecaverdata: {
        nodes: [],
        edges: [],
        combos: [],
      },
      data: {
        nodes: [],
        edges: [],
        combos: [],
      },
      arrlists: [],
      list: [],
      arrlist: [],
      graph: null,
      valuelist: {
        combos: [],
        nodes: [],
        x: 250,
        y: 110,
        x1: 250,
      },
      nodes: [],
      edges: [],
      valuetowlist: {
        combos: [],
        nodes: [],
        x: 250,
        y: 110,
        x1: 250,
      },
      rules: {
        region: [
          {
            required: true,
            message: '请选择关联方式',
            trigger: 'blur',
          },
        ],
      },
      isbool: false,
      modelIdArr: [],
      commitArr: [],
      incidenceRelation: '',
      threerelationArr: [],
      metaModelFieldRelationEntities: [],
      setArr: [],
      concantArr: []
    }
  },
  watch: {
    //父组件数据改变子组件及时更新
    'ruleForm.relationType': function (newval, oldval) {
      if (newval == 1) {
        this.ruleForm.relationTableid = ''
        this.index = newval
        this.list = []
        this.rootList()
        if (this.modelIdArr.length) {
          this.modelIdArr.map((v, i) => {
            deletecaveasmodelid({
              id: v.tableId,
            }).then((res) => {
              if (res.data.code == 200) {
                this.list.push(res.data.data)
                if (this.list.length == 2) {
                  this.caversMeth()
                }
              }
            })
          })
        }
      }
    },
    'ruleForm.relationTableid': function (newval, oldval) {
      if (newval) {
        console.log(newval)
        this.isOpbool = true
        let obj = {}
        this.list = []
        this.rootList()
        this.modelIdArr.map((v, i) => {
          deletecaveasmodelid({
            id: v.tableId,
          }).then((res) => {
            if (res.data.code == 200) {
              this.list.push(res.data.data)
              if (this.list.length == 2) {
                this.arrlist = []
                associationTableDetail({
                  params: {
                    id: newval,
                  },
                }).then((res) => {
                  if (res.data.code == 200) {
                    obj = res.data.data
                    this.arrlist = [
                      { ...this.list[0], lxtype: '111' },
                      { ...obj, lxtype: '222' },
                      { ...this.list[1], lxtype: '333' },
                    ]
                    this.threecavers()
                  }
                })
              }
            }
          })
        })
      } else {
        this.isOpbool = false
      }
    },
    deep: true,
    immediate: true,
  },
  created() {
    this.type = this.$route.query.type
    // 关联表接口
    queryAssociationTable().then((res) => {
      if (res.data.code == 200) {
        this.glaiboa = res.data.data.records
      }
    })
  },
  mounted() {
    this.listoff()
  },
  methods: {
    off() {
      this.timeArr = []
      if (localStorage.getItem('data')) {
        localStorage.removeItem('data')
      }
      if (localStorage.getItem('date')) {
        localStorage.removeItem('date')
      }
      this.ruleForm.relationTableid = undefined
      this.isOpbool = false
      this.data.edges = []
      this.threecaverdata.edges = []
    },
    edgelisthix() {
      let listarrlocal = []
      let list1 = []
      let list = []
      if (localStorage.getItem('data')) {
        listarrlocal = JSON.parse(localStorage.getItem('data'))
        listarrlocal.map((v, i) => {
          if (v.relationType == 1) {
            list.push({
              source: v.primaryFieldid,
              target: v.secondaryFieldid,
              label: v.primarySecondaryConnectedrelationName,
            })
            this.data.edges = list
          }
        })
      } else if (localStorage.getItem('date')) {
        listarrlocal = JSON.parse(localStorage.getItem('date'))
        listarrlocal.map((v, i) => {
          if (v.starttime || v.endtime) {
            let obj = {}
            let obj1 = {}
            if (v.starttime && v.endtime) {
              this.timeArr = [v.starttime, v.endtime]
            }
            if (v.primaryFieldid !== null) {
              obj = {
                id: v.id,
                source: v.primaryFieldid,
                target: v.relationFieldid,
                label: v.relationPrimaryConnectedrelationName,
              }
            }
            list.push(obj)
            if (v.secondaryFieldid !== null) {
              obj1 = {
                id: v.id,
                source: v.relationFieldid,
                target: v.secondaryFieldid,
                label: v.relationSecondaryConnectedrelationName,
              }
            }
            list1.push(obj1)
            console.log([...list, ...list1])
          }
          ;[...list, ...list1].map((v, i) => {
            if (v.id) {
              this.threecaverdata.edges.push(v)
            }
          })
        })
        this.threecavers()
      }
    },
    listoff() {
      this.type = this.$route.query.type
      if (this.type == 'add') {
        this.rootList()
        this.ruleForm.relationType = ''
        this.data.edges = []
        this.threecaverdata.edges = []
      } else if (this.type == 'edit') {
        let modelId = this.$route.query.modelId
        fieldRelation({ modelId: modelId }).then((res) => {
          console.log(res.data.rows)
          this.metaModelFieldRelationEntities = res.data.rows[0].metaModelFieldRelationEntities

          let list = []
          let list1 = []
          this.metaModelFieldRelationEntities.map((v, i) => {
            if (v.relationType == '1') {
              list.push(v)
            } else if (v.relationType == '2') {
              list1.push(v)
            }
          })
          localStorage.setItem('data', JSON.stringify(list))
          localStorage.setItem('date', JSON.stringify(list1))
          this.edgeindex()
        })
      }
    },
    // 无关联表弹框
    sduQwoXudkOpen(item, text) {
      console.log(item, '接收的item,,,,,')
      this.$prompt('请输入关联关系', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',

        inputPlaceholder: text,
      })
        .then(({ value }) => {
          console.log(value, '输入的文字是什么')
          this.updatawrie(value, item)
        })
        .catch((err) => {
          if (err == 'cancel') {
            this.$message({
              type: 'info',
              message: '取消输入',
            })
          } else {
            console.log(err, 'errerreerrrerrererer')
          }
        })
    },
    updatawrie(value, item) {
      console.log(this.data.edges, 'this.data.edgesthis.data.edgesthis.data.edges')
      this.data.edges.map((v, i) => {
        if (v.id == item) {
          console.log(item, '输入文字的item---')
          v.label = value
          this.graph.updateItem(item, v)

          //TODO
          this.relationArr.map((v, i) => {
            if (v.edgeId == item) {
              v.primarySecondaryConnectedrelationName = value
            }
          })
        }
      })
    },
    // 重置
    rootList() {
      ; (this.valuelist = {
        combos: [],
        nodes: [],
        x: 250,
        y: 110,
        x1: 250,
      }),
        (this.valuetowlist = {
          combos: [],
          nodes: [],
          x: 250,
          y: 110,
          x1: 250,
        })
    },
    // 重置字段
    editopen(item) {
      this.dialogVisible = true
    },
    // 提交按钮
    overFun() {
      let arr = []
      let arr1 = []
      let arrlist = []
      if (localStorage.getItem('data') != null) {
        arr = JSON.parse(localStorage.getItem('data'))
      }
      if (this.relationArr.length != 0) {
        arr1 = this.relationArr
      }
      if (this.type == "add") {

        arrlist = [...arr, ...arr1]
        this.setArr = [...arr, ...arr1]

        arrlist = [...this.uniquestItem]
      } else {
        const a = [...arr, ...arr1]
        const editArr = []
        a.forEach(item => {
          if (item.edgeId) {
            editArr.push(item)
          }
        })
        this.setArr = editArr
        arrlist = [...arr, ...this.uniquestItem]
        console.log(arrlist, 'editArreditArr');




        const uniqueData = [];
        const uniqueEdgeIds = {};

        arrlist.forEach(obj => {
          if (obj.edgeId && !uniqueEdgeIds[obj.edgeId]) {
            uniqueData.push(obj);
            uniqueEdgeIds[obj.edgeId] = true;
          }
        });

        console.log(uniqueData);
        const newArr = []
        arr.forEach(item => {
          if (!item.edgeId) {
            newArr.push(item)
          }
        })
        arrlist = [...newArr, ...uniqueData]





      }
      // if(this.type=="edit"){
      //   const editArr = JSON.parse(localStorage.getItem('data'))
      //   editArr.forEach(item => {
      //     if (item.edgeId) {
      //       this.isFirst=false
      //     }
      //   })
      // }




      if (arrlist.length == 0) {
        this.$message.warning('至少选择一条数据')
      } else {
        let isbool = arrlist.every((v, i) => {
          return v.primarySecondaryConnectedrelationName != ''
        })
        if (isbool) {
          const ruleForm = {
            entity: arrlist,
          }
          localStorage.setItem('data', JSON.stringify(ruleForm.entity))
          this.rootList()
          this.dialogVisible = false

          let list1 = []
          if (localStorage.getItem('data')) {
            this.type = this.$route.query.type
            let list = []
            let modelId = this.$route.query.modelId
            fieldRelation({ modelId: modelId }).then((res) => {
              res.data.rows[0].metaModelFieldRelationEntities.map((v, i) => {
                console.log(v, 'v')
                list.push({
                  source: v.primaryFieldid,
                  target: v.secondaryFieldid,
                  label: v.primarySecondaryConnectedrelationName,
                })
              })
              let locallist = JSON.parse(localStorage.getItem('data'))
              locallist.map((v, i) => {
                if (v.relationType == 1) {
                  list1.push({
                    source: v.primaryFieldid,
                    target: v.secondaryFieldid,
                    label: v.primarySecondaryConnectedrelationName,
                  })
                }
              })
              this.data.edges = [...list, ...list1]
            })
          }
        } else {
          this.$message.warning('请输入关联表关系')
        }
      }
    },
    //  提交按钮
    gloverFun() {
      let arr = []
      let arr1 = []
      let arrlist = []
      if (localStorage.getItem('date') !== null) {
        arr = JSON.parse(localStorage.getItem('date'))
      }
      if (this.threerelationArr.length != 0) {
        arr1 = this.threerelationArr
      }

      arrlist = [...arr, ...arr1]

      if (arrlist.length == 0) {
        this.$message.warning('至少选择一条数据')
      } else {
        let isbool = arrlistorlocal.every((v, i) => {
          return v.relationPrimaryConnectedrelationName != '' && v.relationSecondaryConnectedrelationName != ''
        })

        if (isbool) {
          arrlistorlocal.map((v, i) => {
            v.starttime = this.$dayjs(this.timeArr[0]).format('YYYY-MM-DD HH:mm:ss')
            v.endtime = this.$dayjs(this.timeArr[1]).format('YYYY-MM-DD HH:mm:ss')
          })
          const ruleForm = {
            entity: arrlistorlocal,
          }
          localStorage.setItem('date', JSON.stringify(ruleForm.entity))
          this.rootList()
          this.dialogVisible = false
          this.ruleForm.relationTableid = undefined
          this.isOpbool = false
        } else {
          this.$message.warning('请输入关联表关系')
        }
      }
    },
    // 弹框打开，请求
    open(item) {
      this.dialogVisible = true
      this.list = []
      this.rootList()
      this.ruleForm.relationType = '1'
      this.modelIdArr = item
      if (item.length) {
        this.modelIdArr.map((v, i) => {
          deletecaveasmodelid({
            id: v.tableId,
          }).then((res) => {
            if (res.data.code == 200) {
              this.list.push(res.data.data)
              try {
                this.edgeindex()
              } catch (error) { }
              if (this.list.length == 2) {
                this.caversMeth()
              }
            }
          })
        })
      }
    },
    // 关闭弹框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
          this.dialogVisible = false
          this.root()
        })
        .catch((_) => { })
    },
    // g6画布
    caversMeth() {
      let lxtype = ['111', '222']
      this.list.map((v1, i1) => {
        this.valuelist.combos.push({
          lxtype: lxtype[i1],
          padding: [40, 0, 0, 0],
          id: v1.id,
          label: v1.tableName,
          zIndex: 0,
          style: {
            stroke: '#333',
            fill: '#096DD9',
          },
          labelCfg: {
            style: {
              fill: '#fff',
            },
          },
          y: 250,
          x: this.valuelist.x1,
        })
        this.valuelist.x1 = 900

        v1.columnModelEntities.map((v2, i2) => {
          let linkPoints
          if (this.list.length === 2) {
            linkPoints = {
              right: i1 === 0,
              left: i1 !== 0,
            }
          } else if (this.list.length === 3) {
            linkPoints = {
              left: i1 !== 0,
              right: i1 !== 2,
            }
          }

          this.valuelist.nodes.push({
            lxtype: lxtype[i1],
            id: v2.id,
            label: v2.columnName,
            x: 250,
            y: this.valuelist.y,
            comboId: v1.id,
            combolabel: v1.tableName,
            zIndex: 2,
            style: {
              fill: '#fff',
            },
            size: [250, 40],
            linkPoints: linkPoints,
          })
          this.valuelist.y = this.valuelist.y + 40
        })
      })

      this.data = {
        nodes: this.valuelist.nodes,
        edges: this.data.edges,
        combos: this.valuelist.combos,
      }

      const container = this.$refs.container
      const width = container.scrollWidth || 500
      const height = container.scrollHeight || 500
      if (this.graph) {
        this.graph.destroy()
      }
      this.graph = new G6.Graph({
        container,
        width,
        height,
        groupByTypes: true,
        defaultCombo: {
          type: 'rect',
        },

        defaultNode: {
          type: 'rect',

          linkPoints: {
            right: true,
            size: 5,
          },
        },
        defaultEdge: {
          type: 'extra-shape-edge',
          style: {
            radius: 10,
            offset: 310,
            endArrow: true,
            stroke: '#F6BD16',
          },
        },

        modes: {
          default: [
            'drag-canvas',
            'zoom-canvas',
            {
              type: 'create-edge',
              trigger: 'click',
            },
          ],
          custom: ['drag-canvas', 'zoom-canvas'],
        },
      })

      this.list.map((v1, i1) => {
        this.graph.updateCombo(v1.id, {
          width: 200,
        })
      })

      this.graph.data(this.data)

      this.graph.on('edge:dblclick', (evt) => {
        const edge = evt.item._cfg.model.id // 获取被双击的连线实例
        let text = evt.item._cfg.model.label
        this.sduQwoXudkOpen(edge, text)
      })

      this.graph.on('aftercreateedge', (evt) => {
        console.log(evt, 'aftercreateedge')
        let sourceComboId = evt.edge._cfg.sourceNode._cfg.model.comboId
        let targetComboId = evt.edge._cfg.targetNode._cfg.model.comboId
        if (sourceComboId == targetComboId) {
          const edgeId = evt.edge._cfg.id
          this.$message({
            message: '不允许连接同表!',
            type: 'warning',
          })
          setTimeout(() => {
            this.graph.removeItem(edgeId)
          }, 0)
        } else {
          const edge = evt.edge // 获取创建的连线实例
          const edgeId = edge._cfg.id
          // 获取连线的源节点和目标节点 ID
          const sourceNode = edge.getSource().getModel()
          const targetNode = edge.getTarget().getModel()
          // 打印开始和结束节点信息

          this.data.edges.push({
            source: sourceNode.id,
            target: targetNode.id,
            edgeId: edgeId,
            id: edgeId,
            label: '请输入关联关系',
          })
          this.relationArr.push({
            edgeId: edge._cfg.id,
            modelId: this.$route.query.modelId,
            relationType: '1',
            primarySecondaryConnectedrelationName: '',
            // // 连接id
            // edgeId: edgeId,
            // 主表
            primaryTableid: sourceNode.comboId,
            primaryTablename: sourceNode.combolabel,

            // 主表字段
            primaryFieldid: sourceNode.id,
            primaryFieldname: sourceNode.label,

            //次表
            secondaryTableid: targetNode.comboId,
            secondaryTablename: targetNode.combolabel,

            //次表字段
            secondaryFieldid: targetNode.id,
            secondaryFieldname: targetNode.label,
          })
          this.data.edges.map((v, i) => {
            // 更新线
            if (v.source !== null && v.target !== null && v.edgeId !== null && v.id !== null) {
              this.graph.updateItem(edgeId, v)
            }
          })
        }
      })

      this.graph.on('edge:mouseenter', (e) => {
        console.log(e)
        const nodeItem = e.item
        const sourceNode = nodeItem.getSource()
        const targetNode = nodeItem.getTarget()
        console.log(sourceNode, targetNode)
        const sourceModel = sourceNode.getModel()
        const targetModel = targetNode.getModel()

        const x1 = sourceModel.x
        const y1 = sourceModel.y
        const x2 = targetModel.x
        const y2 = targetModel.y

        const cx = (x1 + x2) / 2
        const cy = (y1 + y2) / 2
        const length = x2 - x1
        const width = y2 - y1
        const midX = cx - length / 4
        const midY = cy - width / 2.5

        const model = nodeItem.getModel()
        const group = nodeItem.getContainer()
        const deleteButton = group.addShape('circle', {
          attrs: {
            x: midX,
            y: midY,
            r: 7,
            stroke: '#f00',
            fill: '#f00',
            cursor: 'pointer',
          },
        })
        const text = group.addShape('text', {
          attrs: {
            x: midX,
            y: midY + 2,
            text: 'X',
            fill: '#fff',
            fontSize: 12,
            fontWeight: 600,
            textAlign: 'center',
            textBaseline: 'middle',
            cursor: 'pointer',
          },
          name: 'text-shape',
        })
        text.on('click', (ect) => {
          let item = [sourceNode, targetNode]
          this.removeItem(item)
          this.graph.removeItem(nodeItem)

        })
        deleteButton.on('click', (ect) => {
          let item = [sourceNode, targetNode]
          this.removeItem(item)
          this.graph.removeItem(nodeItem)
        })
      })

      this.graph.render()
      if (typeof window !== 'undefined')
        window.onresize = () => {
          if (!this.graph || this.graph.get('destroyed')) return
          if (!container || !container.scrollWidth || !container.scrollHeight) return
        }
    },
    // 有关联弹框
    threecaversduQwoXudkOpen(item, edge) {
      console.log(item, '文字是什么')
      this.$prompt('请输入关联关系', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          this.threecaverupdatawrie(value, item, edge)
        })
        .catch((err) => {
          if (err) {
          } else {
            this.$message({
              type: 'info',
              message: '取消输入',
            })
          }
        })
    },
    threecaverupdatawrie(value, item, edge) {
      console.log(this.threecaverdata.edges)
      this.threecaverdata.edges.map((v, i) => {
        if (v.source == item[0] && v.target == item[1]) {
          v.label = value
          this.graph.updateItem(edge, v)
          this.arrlists.map((v1, i1) => {
            if (v1.primaryFieldid == item[0] && v1.relationFieldid == item[1] && v1.lxtype1 == '111') {
              v1.relationPrimaryConnectedrelationName = value
            }
            if (v1.relationFieldid == item[0] && v1.secondaryFieldid == item[1] && v1.lxtype2 == '222') {
              v1.relationSecondaryConnectedrelationName = value
            }
          })
        }
      })
    },
    // 有关联图形
    threecavers() {
      this.arrlist.map((v1, i1) => {
        this.valuetowlist.combos.push({
          padding: [40, 0, 0, 0],
          id: v1.id,
          label: v1.tableName,
          zIndex: 0, // 设置 zIndex 值为 0
          style: {
            stroke: '#333',
            fill: '#096DD9',
          },
          labelCfg: {
            style: {
              fill: '#fff',
            },
          },
          y: 150,
          x: this.valuetowlist.x1,
        })
        this.valuetowlist.x1 = this.valuetowlist.x1 + 600
        v1.columnModelEntities.map((v2, i2) => {
          let linkPoints
          if (this.arrlist.length === 2) {
            linkPoints = {
              right: i1 === 0,
              left: i1 !== 0,
            }
          } else if (this.arrlist.length === 3) {
            linkPoints = {
              left: i1 !== 0,
              right: i1 !== 2,
            }
          }
          this.valuetowlist.nodes.push({
            lxtype: v1.lxtype,
            id: v2.id,

            label: v2.columnName,
            x: this.valuetowlist.x,
            y: this.valuetowlist.y,
            comboId: v1.id,
            combolabel: v1.tableName,
            zIndex: 2, // 设置 zIndex 值为 2

            size: [250, 40],
            linkPoints: linkPoints,
          })
          this.valuetowlist.y = this.valuetowlist.y + 40
        })
      })

      this.threecaverdata = {
        nodes: this.valuetowlist.nodes,
        edges: this.threecaverdata.edges,
        combos: this.valuetowlist.combos,
      }
      if (this.graph) {
        this.graph.destroy()
      }

      const container = this.$refs.associationTableContainer
      const width = container.scrollWidth || 500
      const height = container.scrollHeight || 500
      this.graph = new G6.Graph({
        container,
        width,
        height,
        groupByTypes: true,
        defaultCombo: {
          type: 'rect',
        },

        defaultNode: {
          type: 'rect',

          linkPoints: {
            right: true,
            size: 5,
          },
        },
        defaultEdge: {
          type: 'extra-shape-edge',
          style: {
            radius: 10,
            offset: 30,
            endArrow: true,
            stroke: '#F6BD16',
          },
        },
        comboStateStyles: {
          dragenter: {
            lineWidth: 4,
            stroke: '',
          },
        },
        modes: {
          default: [
            'drag-canvas',
            'zoom-canvas',
            {
              type: 'create-edge',
              trigger: 'click',

              shouldBegin: (e) => {
                if (e.item._cfg.model.lxtype == '222') {
                  return true
                } else if (e.item._cfg.model.lxtype == '1111' || e.item._cfg.model.lxtype == '333') {
                  return false
                }
              },
              shouldEnd: (e) => {
                if (e.item._cfg.model.lxtype == '222') {
                  return false
                } else {
                  return true
                }
              },
            },
          ],
          custom: ['drag-canvas', 'zoom-canvas'],
        },
      })

      this.graph.on('edge:dblclick', (evt) => {
        const edge = evt.item._cfg.model.edgeId // 获取被双击的连线实例
        const edgeItem = evt.item // 获取连接线的图形对象
        const sourceNode = edgeItem.getSource() // 获取连接线的起始节点
        const targetNode = edgeItem.getTarget() // 获取连接线的结束节点
        console.log('起点节点：', sourceNode)
        console.log('终点节点：', targetNode)
        this.threecaversduQwoXudkOpen([sourceNode._cfg.id, targetNode._cfg.id], edge)
      })

      this.graph.on('aftercreateedge', (evt) => {
        const edge = evt.edge // 获取创建的连线实例
        const edgeId = edge._cfg.id
        // 获取连线的源节点和目标节点 ID
        const sourceNode = edge.getSource().getModel()
        const targetNode = edge.getTarget().getModel()

        this.threecaverdata.edges.push({
          source: sourceNode.id,
          target: targetNode.id,
          edgeId: edgeId,
          id: edgeId,
          label: '请选择关联字段',
        })

        let list = []
        let list3 = []
        if (targetNode.lxtype == '111') {
          list.push({
            edgeId: edge._cfg.id,
            modelId: this.$route.query.modelId,
            primaryTableid: sourceNode.comboId,
            primaryTablename: sourceNode.combolabel,
            primaryFieldid: sourceNode.id,
            primaryFieldname: sourceNode.label,
            relationTableid: targetNode.comboId,
            relationTablename: targetNode.combolabel,
            relationFieldid: targetNode.id,
            relationFieldname: targetNode.label,
            lxtype1: '111',
            relationType: '2',
            relationPrimaryConnectedrelationName: '',
          })
        } else if (targetNode.lxtype == '333') {
          list3.push({
            lxtype2: '222',
            edgeId: edge._cfg.id,
            modelId: this.$route.query.modelId,
            relationTableid: sourceNode.comboId,
            relationTablename: sourceNode.combolabel,
            relationFieldid: sourceNode.id,
            relationFieldname: sourceNode.label,
            secondaryTableid: targetNode.comboId,
            secondaryTablename: targetNode.combolabel,
            secondaryFieldid: targetNode.id,
            secondaryFieldname: targetNode.label,
            relationSecondaryConnectedrelationName: '',
            relationType: '2',
          })
        }
        list.map((v, i) => {
          this.arrlists.push(v)
        })

        list3.map((v, i) => {
          this.arrlists.push(v)
        })
        this.threerelationArr = this.arrlists

        this.threecaverdata.edges.map((v, i) => {
          // 更新线
          console.log(edgeId, v)
          if (v.source !== null && v.target !== null && v.edgeId !== null && v.id !== null) {
            this.graph.updateItem(edgeId, v)
          }
        })
      })

      this.graph.on('edge:mouseenter', (e) => {
        const nodeItem = e.item
        const sourceNode = nodeItem.getSource()
        const targetNode = nodeItem.getTarget()
        const sourceModel = sourceNode.getModel()
        const targetModel = targetNode.getModel()

        const x1 = sourceModel.x
        const y1 = sourceModel.y
        const x2 = targetModel.x
        const y2 = targetModel.y

        console.log('x1', x1, 'y1', y1, 'x2', x2, 'y2', y2)
        const cx = (x1 + x2) / 2
        const cy = (y1 + y2) / 2
        const length = x2 - x1
        const width = y2 - y1
        const midX = cx - length / 4
        const midY = cy - width / 2.5

        const model = nodeItem.getModel()
        const group = nodeItem.getContainer()
        const deleteButton = group.addShape('circle', {
          attrs: {
            x: midX,
            y: midY,
            r: 7,
            stroke: '#f00',
            fill: '#f00',
            cursor: 'pointer',
          },
        })
        const text = group.addShape('text', {
          attrs: {
            x: midX,
            y: midY + 2,
            text: 'X',
            fill: '#fff',
            fontSize: 12,
            fontWeight: 600,
            textAlign: 'center',
            textBaseline: 'middle',
            cursor: 'pointer',
          },
          name: 'text-shape',
        })
        text.on('click', () => {
          let item = [sourceNode, targetNode]
          this.removeItem1(item)
          this.graph.removeItem(nodeItem)
        })
        deleteButton.on('click', () => {
          let item = [sourceNode, targetNode]
          this.removeItem1(item)
          this.graph.removeItem(nodeItem)
        })
      })

      this.graph.on('node:mouseleave', (e) => {
        const nodeItem = e.item
        if (nodeItem.deleteButton) {
          nodeItem.deleteButton.remove()
          nodeItem.deleteButton = null
        }
      })
      this.graph.data(this.threecaverdata)
      this.graph.render()
      if (typeof window !== 'undefined')
        window.onresize = () => {
          if (!this.graph || this.graph.get('destroyed')) return
          if (!container || !container.scrollWidth || !container.scrollHeight) return
          this.graph.changeSize(container.scrollWidth, container.scrollHeight - 20)
        }
    },
    edgeindex() {
      if (JSON.parse(localStorage.getItem('data'))) {
        let list = []
        JSON.parse(localStorage.getItem('data')).map((v, i) => {
          list.push({
            source: v.primaryFieldid,
            target: v.secondaryFieldid,
            label: v.primarySecondaryConnectedrelationName,
          })
          this.data.edges = list
        })
      }
      if (JSON.parse(localStorage.getItem('date'))) {
        let list = []
        let list1 = []
        JSON.parse(localStorage.getItem('date')).map((v, i) => {
          if (v.relationType == 2) {
            let obj = {}
            let obj1 = {}
            if (v.starttime) {
              this.timeArr = [v.starttime, v.endtime]
            }
            if (v.primaryFieldid !== null) {
              obj = {
                id: v.id,
                source: v.primaryFieldid,
                target: v.relationFieldid,
                label: v.relationPrimaryConnectedrelationName,
              }
            }
            list.push(obj)
            if (v.secondaryFieldid !== null) {
              obj1 = {
                id: v.id,
                source: v.relationFieldid,
                target: v.secondaryFieldid,
                label: v.relationSecondaryConnectedrelationName,
              }
            }
            list1.push(obj1)
            console.log([...list, ...list1])
          }
          ;[...list, ...list1].map((v, i) => {
            if (v.id) {
              this.threecaverdata.edges.push(v)
            }
          })
        })
      }
      if (this.threecaverdata.edges) {
        this.threecavers()
      } else {
        this.caversMeth()
      }
    },
    //删除节点
    removeItem(item) {
      let arr = []
      let arr1 = []
      let arr2 = []
      let arrlist = []

      if (this.relationArr.length != 0) {
        arr1 = this.relationArr
        arr1.map((v, i) => {
          if (v.primaryFieldid == item[0]._cfg.id && v.secondaryFieldid == item[1]._cfg.id) {
            arr1.splice(i, 1)
          }
        })
      }
      if (localStorage.getItem('data')) {
        arr2 = JSON.parse(localStorage.getItem('data'))
        arr2.map((v, i) => {
          if (v.primaryFieldid == item[0]._cfg.id && v.secondaryFieldid == item[1]._cfg.id) {
            arr2.splice(i, 1)
          }
        })
      }
      if (this.type == 'add') {
        this.concantArr = [...arr1, ...arr2]
        console.log(this.concantArr, 'this.concantArrthis.concantArr');
        localStorage.setItem('data', JSON.stringify(this.conArr))
      } else {

        localStorage.setItem('data', JSON.stringify([...arr1, ...arr2]))
        //     if(this.isFirst){
        //     }else{
        //       this.concantArr = [...arr1, ...arr2]
        // console.log(this.concantArr,'this.concantArrthis.concantArr');
        // localStorage.setItem('data', JSON.stringify(this.conArr))
        //     }
      }



    },
    removeItem1(item) {
      let arr1 = []
      let arr2 = []

      if (this.threerelationArr.length != 0) {
        arr1 = this.threerelationArr
        arr1.map((v, i) => {
          if ((v.primaryFieldid == item[0]._cfg.id && v.relationFieldid == item[1]._cfg.id) || (v.relationFieldid == item[0]._cfg.id && v.secondaryFieldid == item[1]._cfg.id)) {
            arr1.splice(i, 1)
          }
        })
      }
      if (localStorage.getItem('date')) {
        arr2 = JSON.parse(localStorage.getItem('date'))
        arr2.map((v, i) => {
          if ((v.primaryFieldid == item[0]._cfg.id && v.relationFieldid == item[1]._cfg.id) || (v.relationFieldid == item[0]._cfg.id && v.secondaryFieldid == item[1]._cfg.id)) {
            arr2.splice(i, 1)
          }
        })
      }

      localStorage.setItem('date', JSON.stringify([...arr1, ...arr2]))
    },
  },
}
</script>

<style lang="sass" scoped></style>
